package com.laomo.lib_music;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.provider.MediaStore;

import com.google.gson.Gson;

import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/**
 * LibMusicPlugin
 */
public class LibMusicPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware, OnMusicPlayListener {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private MethodChannel mMethodChannel;
    private MicInterface mMicInterface;
    private Activity activity;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        mMethodChannel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "lib_music");
        mMethodChannel.setMethodCallHandler(this);

        //麦克风数据
        mMicInterface = new MicInterface(flutterPluginBinding.getBinaryMessenger());
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        Map<String, Object> args;
        String address;
        String serverUuid;
        String uuid;
        Map<String, Object> map;
        switch (call.method) {
            case "startPlay":
                MusicPlayManager.getInstance().setOnMusicPlayListener(this);
                args = (Map<String, Object>) call.arguments;
                MusicPlayManager.getInstance().startPlay(activity, Uri.parse((String) args.get("uri")));
                break;
            case "pausePlay":
                MusicPlayManager.getInstance().pausePlay();
                break;
            case "stopPlay":
                MusicPlayManager.getInstance().stopPlay();
                break;
            case "seekTo":
                args = (Map<String, Object>) call.arguments;
                MusicPlayManager.getInstance().seekTo((int) args.get("progress"));
                break;
            case "continuePlay":
                MusicPlayManager.getInstance().continuePlay();
                break;
            case "setVolume":
                args = (Map<String, Object>) call.arguments;
                MusicPlayManager.getInstance().setVolume(((int) args.get("volume")) / 100f);
                break;
            case "getPlatformVersion":
                result.success("Android " + android.os.Build.VERSION.RELEASE);
                break;
            case "getMusicList":
                //扫描音乐
                List<Map<String, Object>> list = new ArrayList<>();
                ContentResolver contentResolver = activity.getContentResolver();
                Uri collection = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                    collection = MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
                } else {
                    collection = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String[] projection = new String[]{
                        MediaStore.Audio.Media._ID,
                        MediaStore.Audio.Media.TITLE,
                        MediaStore.Audio.Media.ARTIST,
                        MediaStore.Audio.Media.DURATION,
                        MediaStore.Audio.Media.DATA  // 注意：在Android 10及以上，使用DATA字段可能需要额外的权限或考虑分区存储的影响。
                };

                try (Cursor cursor = contentResolver.query(collection, projection, null, null, null)) {
                    if (cursor != null && cursor.moveToFirst()) {
                        do {
                            long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
                            String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                            String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                            int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
                            String data = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));  // 获取文件路径（在Android 10及以上可能需要特别注意）
                            // 处理音频文件，例如显示在列表中或进行其他操作

                            Map<String, Object> itemMap = new HashMap<>();
                            itemMap.put("title", title);
                            itemMap.put("artist", artist);
                            itemMap.put("url", data);
                            itemMap.put("duration", duration);
                            list.add(itemMap);
                        } while (cursor.moveToNext());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                result.success(list);
                break;
            default:
                result.notImplemented();
        }
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        mMethodChannel.setMethodCallHandler(null);
    }

    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
        activity = binding.getActivity();
    }

    @Override
    public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
    }

    @Override
    public void onDetachedFromActivity() {
    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {
    }


    @Override
    public void onStartPlay() {
        mMethodChannel.invokeMethod("onStartPlay", null);
    }

    @Override
    public void onPausePlay() {
        mMethodChannel.invokeMethod("onPausePlay", null);
    }

    @Override
    public void onPlayComplete() {
        mMethodChannel.invokeMethod("onPlayComplete", null);
    }

    @Override
    public void onProgress(int progress) {
        mMethodChannel.invokeMethod("onProgress", progress);
    }

    @Override
    public void onFftDataCapture(byte[] fft) {
        mMethodChannel.invokeMethod("onFftDataCapture", fft);
    }

    /**
     * 预处理数据
     *
     * @return
     */
    private static byte[] readyData(byte[] fft) {
        byte[] newData = new byte[128];
        byte abs;
        for (int i = 0; i < 128; i++) {
            abs = (byte) Math.abs(fft[i]);
            //描述：Math.abs -128时越界
            newData[i] = abs < 0 ? 127 : abs;
        }
        return newData;
    }

    @Override
    public void onWaveFormDataCapture(byte[] waveform) {
        mMethodChannel.invokeMethod("onWaveFormDataCapture", waveform);
    }
}
